package com.zjhome.cloudnote.service.impl;

import java.io.IOException;
import java.util.ArrayList;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.zjhome.cloudnote.util.SerializeUtil;

import lombok.AllArgsConstructor;

/**
 * 自定义验证组件
 * 
 * @author 0283000121
 *
 */
@AllArgsConstructor
public class CustomAuthenticationProvider implements AuthenticationProvider {
	
	private UserDetailsService 		userDetailsService;
	private BCryptPasswordEncoder	bCryptPasswordEncoder;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// 获取认证的用户名  和 密码
		String username = authentication.getName();
		String password = authentication.getCredentials().toString();
		
		// 认证逻辑
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		if (null != userDetails) {
			if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
				// 这里设置权限和角色
				ArrayList<GrantedAuthority> authorities = new ArrayList<>();
				authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
				authorities.add(new GrantedAuthorityImpl("ROLE_WRITE"));
				
				// 生成令牌 这里令牌里面存入了：name,password,authorities，还可以放一些其他自定义数据
//				Authentication auth = new UsernamePasswordAuthenticationToken(username, password, authorities);				
				Authentication auth = auth = new UsernamePasswordAuthenticationToken(username, password, authorities);
				return auth;				
			}
			else {
				throw new BadCredentialsException("密码错误");
			}
		}
		else {
			throw new UsernameNotFoundException("用户不存在");
		}
	}

	/**
	 * 是否可以提供输入类型的认证服务
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		// 
		return authentication.equals(UsernamePasswordAuthenticationToken.class);		
	}

}
